package com.sj.uabrowser.mvp.main.view.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sj.uabrowser.BuildConfig;
import com.sj.uabrowser.MainActivity;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.NetworkUtils;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.Util;
import com.sj.uabrowser.framework.LazyLoadFragment;
import com.sj.uabrowser.meta.CommenLoadMoreView;
import com.sj.uabrowser.mvp.main.bean.News;
import com.sj.uabrowser.mvp.main.contract.NewsContract;
import com.sj.uabrowser.mvp.main.presenter.NewsPresenter;
import com.sj.uabrowser.mvp.main.view.act.NewsDetailAct;
import com.sj.uabrowser.mvp.main.view.adp.NewsAdp;
import com.umeng.analytics.MobclickAgent;
import com.vondear.rxtool.RxNetTool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFragment extends LazyLoadFragment<NewsContract.Presenter> implements NewsContract.View {

    private static final int REQUESTCODE_NETSETTTINS = 1;
    private String title;
    private RecyclerView rvNews;
    MultipleStatusView mLayoutStatusView;
    SmartRefreshLayout mRefreshLayout;
    private View classicsHeader;
    private View ivBackTop;

    private List<News> datas = new ArrayList<>();
    private NewsAdp adp = new NewsAdp(datas);
    private String id;//翻页用

    public NewsFragment() {
        // Required empty public constructor
    }

    private int page = 1;
    private int freshPage = 0;//请求不能传0

//    private static NewsFragment sNewsFragment;


    public static NewsFragment getInstance(String title) {
//        if(sNewsFragment==null){
        NewsFragment sNewsFragment = new NewsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        sNewsFragment.setArguments(bundle);
//        }
        return sNewsFragment;
    }

    private void fetchNews(final int page) {
        if (presenter != null) {
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("page", page);
            params.put("category", title);
            if(!TextUtils.isEmpty(id))
            params.put("rowid", id);
            params.put("appname", getResources().getString(R.string.app_name));
            params.put("pkgname", getActivity().getApplicationContext().getPackageName());
            params.put("app_version", Util.getVersionName());
            params.put("os", 1);
            params.put("osv", Util.getDeviceSDK());
            String uuid = SPUtil.get(getActivity(), SPUtil.UUID, "");
            if(!TextUtils.isEmpty(uuid))
            params.put("imei", uuid);
//            params.put("anid", "");
            params.put("make", Util.getManufactor());
            params.put("model", Util.getDeviceModel());
            params.put("sw", Util.getDisplayMetrics().widthPixels);
            params.put("sh", Util.getDisplayMetrics().heightPixels);
            params.put("devicetype", 1);
//            params.put("ip", "");
            params.put("ua", "X5");
            params.put("conn", NetworkUtils.getNetworkType(getActivity()));
//            params.put("carrier", "");
//            params.put("lon", "");
//            params.put("lat", "");
            params.put("uChannel",Util.getChannelName());
            params.put("pid", Constant.PID);
            presenter.fetchNews(params);
        }
    }

    public void isDownRefresh(boolean isDown) {
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableRefresh(isDown);
            mRefreshLayout.setEnableHeaderTranslationContent(isDown);
            if (rvNews != null) rvNews.scrollToPosition(0);

        }
    }


    @Override
    protected int setContentView() {
        return R.layout.fragment_news;
    }

    @Override
    protected void lazyLoad() {
        if (datas.size() == 0) {
            if (RxNetTool.isNetworkAvailable(act)) {
                fetchNews(page++);
            } else {
                String newsStr = SPUtil.get(act, title, "");
                if(TextUtils.isEmpty(newsStr)){
                    mLayoutStatusView.showNoNetwork();
                    mLayoutStatusView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(RxNetTool.isNetworkAvailable(act)){
                                fetchNews(page=1);
                            }else{
                                startActivityForResult(new Intent(
                                        android.provider.Settings.ACTION_WIRELESS_SETTINGS), REQUESTCODE_NETSETTTINS);
                            }
                        }
                    });
                }else {
                    List<News> news = new GsonBuilder().create().fromJson(newsStr, new TypeToken<List<News>>() {
                    }.getType());
                    showNews(news);
                }
            }
        }
    }

    @Override
    public NewsContract.Presenter createPresenter() {
        return new NewsPresenter(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUESTCODE_NETSETTTINS){
            if(RxNetTool.isNetworkAvailable(act)){
                fetchNews(page=1);
            }
        }
    }

    @Override
    public void setView() {
        title = getArguments().getString("title");
        rvNews = (RecyclerView) findViewById(R.id.rvNews);
        ivBackTop = findViewById(R.id.iv_backtop);
        mRefreshLayout = (SmartRefreshLayout) findViewById(R.id.mRefreshLayout);
        classicsHeader = findViewById(R.id.classicsHeader);
        mLayoutStatusView = (MultipleStatusView) findViewById(R.id.multipleStatusView);
        rvNews.setLayoutManager(new LinearLayoutManager(getActivity()));
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.divider));
        rvNews.addItemDecoration(dividerItemDecoration);
        rvNews.setAdapter(adp);
        adp.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                new CountDownTimer(500, 500) {

                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {//上拉
                        fetchNews(page++);
                    }
                }.start();
            }
        }, rvNews);
        adp.setLoadMoreView(new CommenLoadMoreView());
        //内容跟随偏移
        mRefreshLayout.setEnableHeaderTranslationContent(true);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {//下拉
//                classicsHeader.setVisibility(View.VISIBLE);
                page = 1;
                id = "";
                fetchNews(--freshPage);
            }
        });

        //设置下拉刷新主题颜色
        mRefreshLayout.setPrimaryColorsId(R.color.color_lighter_gray, R.color.color_title_bg);
        mLayoutStatusView.showLoading();
        adp.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                News bean = datas.get(position);
                if (BuildConfig.UM) {
                    Map<String, String> params = new HashMap<>();
                    params.put("title", bean.getTitle());
                    params.put("type", title);
                    String eventid = bean.isIs_ad() ? "xinxiliu.guanggao" : "xinxiliu.neirong";
                    MobclickAgent.onEvent(getActivity(), eventid, params);
                }
                Intent intent = new Intent(getActivity(), NewsDetailAct.class);
//                intent.putExtra("url", bean.getClk_url());
//                List<String> list = bean.getImp_tracking();
//                if (list != null && list.size() > 0)
//                    intent.putExtra("imp", list.get(0));
                intent.putExtra("news",bean);
                startActivity(intent);
            }
        });
        ivBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rvNews.scrollToPosition(0);
                ivBackTop.setVisibility(View.GONE);
            }
        });
        //设置RecyclerView滑动监听器 addOnScrollListener(),其中setOnScrollListener()方法已过时
        rvNews.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //获得recyclerView的线性布局管理器
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //获取到第一个item的显示的下标  不等于0表示第一个item处于不可见状态 说明列表没有滑动到顶部 显示回到顶部按钮
                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 判断是否滚动超过一屏
                    if (firstVisibleItemPosition == 0) {
                        ivBackTop.setVisibility(View.GONE);
                    } else {
                        //显示回到顶部按钮
                        ivBackTop.setVisibility(View.VISIBLE);
                    }
                    //获取RecyclerView滑动时候的状态
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
                    ivBackTop.setVisibility(View.GONE);
                }
            }
        });
        isDownRefresh(!MainActivity.mIsScroll);

    }

    @Override
    public void setData() {

    }

    @Override
    public void showNews(List<News> newsBeans) {
        mRefreshLayout.finishRefresh();
        adp.loadMoreComplete();
        if (newsBeans != null && newsBeans.size() > 0) {
            id = newsBeans.get(newsBeans.size() - 1).getId();
        }
        if (page < 0) datas.clear();
        datas.addAll(newsBeans);
        if (newsBeans == null || newsBeans.size() == 0)
            adp.loadMoreEnd();
        if (adp != null) {
            adp.notifyDataSetChanged();
            mLayoutStatusView.showContent();
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            ((MainActivity) getActivity()).updateNewsAdp();
        }catch (Exception e){}
    }

    public void updateFontSize() {
        if(adp!=null)adp.notifyDataSetChanged();
    }

    @Override
    public void showErrors() {
        mRefreshLayout.finishRefresh();
    }

}
